package gutils

import (
	"strings"
	"time"
)

var (
	// 默认东八区(8)
	TimeZone = 8
)

func init() {
	// 初始化时区
	var cstZone = time.FixedZone("CST", TimeZone*3600)
	time.Local = cstZone
}

func timezone() int64 {
	return int64(TimeZone)
}

func formatTimeZone() time.Time {
	return time.Now()
}

func SleepMillisecond(num time.Duration) {
	time.Sleep(time.Millisecond * num)
}

func GetNowTimeStamp() int64 {
	return formatTimeZone().Unix()
}

func GetNowTimeStampMillisecond() int64 {
	return formatTimeZone().UnixNano() / 1e6
}

func GetNowTimeStampNanosecond() int64 {
	return formatTimeZone().UnixNano()
}

func GetNowWeekday() (string, int) {
	dt := formatTimeZone().Weekday()
	return dt.String(), int(dt)
}

func GetDateTimeList(timeStamp int64) (string, string, string) {
	if timeStamp == 0 {
		timeStamp = GetNowTimeStamp()
	}
	timeStamp = timeStamp + int64(timezone()*3600)
	date := time.Unix(timeStamp, 0).UTC().Format("2006-01-02")
	time := time.Unix(timeStamp, 0).UTC().Format("15:04:05")
	return date, time, date + " " + time
}

func GetDateTime(timeStamp int64) string {
	_, _, date_time := GetDateTimeList(timeStamp)
	return date_time
}

// show >> "ymdhis"
func GetDateTimeFormat(timeStamp int64, show string, separator string) string {
	format_map := map[string]string{
		"y": "2006",
		"m": "01",
		"d": "02",
		"h": "15",
		"i": "04",
		"s": "05",
	}
	if show == "" {
		show = "ymdhis"
	}
	if timeStamp == 0 {
		timeStamp = GetNowTimeStamp()
	}
	timeStamp = timeStamp + int64(timezone()*3600)
	keys := strings.Split(show, "")
	format_keys := []string{}
	for _, v := range keys {
		if format_map[v] != "" {
			format_keys = append(format_keys, format_map[v])
		}
	}
	format_keys_str := strings.Join(format_keys, separator)
	dates := time.Unix(timeStamp, 0).UTC().Format(format_keys_str)
	return dates
}

// 比较参数1是否大于等于参数2
func CompareDateTimeGTE(datetime1, dateTime2 string) bool {
	//先把时间字符串格式化成相同的时间类型
	t1, _ := time.Parse("2006-01-02 15:04:05", datetime1)
	t2, _ := time.Parse("2006-01-02 15:04:05", dateTime2)
	if t2.Before(t1) { // t2 < t1
		return true
	} else {
		return false
	}
}

// datetime 字符串 加 时间戳(秒)
func ComputeDateTime(datetime string, timestamp int64) string {
	t, _ := time.Parse("2006-01-02 15:04:05", datetime)
	return t.Add(time.Duration(timestamp) * time.Second).Format("2006-01-02 15:04:05")
}
